<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入昵称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-input v-model="queryParams.department" placeholder="请输入部门" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="queryParams.city" placeholder="请输入城市" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="是否管理员" prop="isAdmin">
        <el-select style="width: 100px;" v-model="queryParams.isAdmin" class="m-2" placeholder="请选择入群填写项" size="normal"
          @changge="handleIsAdmmin">
          <el-option v-for="item in isAdminType" :key="item.value" :label="item.label" :value="parseInt(item.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['main:member:add']">新增</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column type="image" label="头像" align="center" prop="avatar">
        <template #default="scope">
          <img :src="scope.row.avatar" alt="图片飞走了" style="width: 50px;height: 50px;" srcset="">
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phonenumber" />
      <el-table-column label="部门职位" align="center" prop="department" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="qq" align="center" prop="qq" />
      <el-table-column label="推荐人名称" align="center" prop="recommend" />

      <!-- <el-table-column label="学校" align="center" prop="school" />
              <el-table-column label="家乡" align="center" prop="home" />
              <el-table-column label="城市" align="center" prop="city" />
              <el-table-column label="生日" align="center" prop="birthday" /> -->
      <!-- <el-table-column label="推荐人名称" align="center" prop="recommend" />
              <el-table-column label="到期时间" align="center" prop="expireTime" /> -->
      <!-- <el-table-column label="奉献" align="center" prop="dedication" />
              <el-table-column label="分享" align="center" prop="shareNum" />
              <el-table-column label="引荐" align="center" prop="pullNum" /> -->
      <el-table-column label="是否管理员" align="center" prop="isAdmin">
        <template #default="scope">
          <span v-if="scope.row.isAdmin == 0">否</span>
          <span v-if="scope.row.isAdmin == 1">是</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status == 0">正常</span>
          <span v-if="scope.row.status == 1">待续费</span>
        </template>
      </el-table-column>
      <el-table-column label="公司" align="center" prop="company" />
      <el-table-column label="公司介绍" align="center" prop="summary" />
      <el-table-column label="特长" align="center" prop="speciality" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="加入时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="CircleCheck" @click="handleInfo(scope.row)"
            v-hasPermi="['main:member:edit']">查看详情</el-button>
          <el-button v-if="scope.row.isGroup == 0" link type="primary" icon="edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['main:member:edit']">{{
              scope.row.isAdmin == 0 ? "设为管理员" : "取消管理员"
            }}</el-button>
          <el-button v-if="scope.row.isAdmin == 1" link type="primary" icon="edit" @click="handlePower(scope.row)"
            v-hasPermi="['main:member:edit']">权限设置</el-button>
          <el-button v-if="scope.row.isGroup == 0" link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['main:member:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 查看详情 -->
    <el-dialog title="查看详情" v-model="viewOpen" width="960px" append-to-body :close-on-click-modal="false"
      @close="cancel">
      <el-skeleton :loading="loading" animated :count="1">
        <template #template>
          <div style="display: flex">
            <el-skeleton-item variant="avatar" style="width: 400px; height: 267px; margin-right: 20px" />
            <div>
              <el-skeleton-item variant="h3" style="margin-bottom: 16px" />
              <el-skeleton-item variant="text" />
              <el-skeleton-item variant="text" style="width: 80%" />
            </div>
          </div>
        </template>
        <template #default>
          <div style="display: flex; align-items: start">
            <img :src="form.backImage" class="image" style="width: 400px; height: auto; margin-right: 20px" />
            <div style="flex-grow: 1">
              <div style="margin-bottom: 20px">
                <span style="font-size: 18px; font-weight: bold">基本信息</span>
                <ul style="list-style-type: none; padding: 0; margin-top: 10px">
                  <li style="margin-bottom: 8px">
                    成员名称：{{ form.nickName }}
                  </li>
                  <li style="margin-bottom: 8px">
                    手机号：{{ form.phonenumber }}
                  </li>
                  <li style="margin-bottom: 8px">微信号：{{ form.wx }}</li>
                  <li style="margin-bottom: 8px">qq：{{ form.qq }}</li>
                  <li style="margin-bottom: 8px">邮箱{{ form.email }}</li>
                  <li style="margin-bottom: 8px">家乡{{ form.home }}</li>
                </ul>
              </div>
            </div>
          </div>
        </template>
      </el-skeleton>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门职位" prop="department">
          <el-input v-model="form.department" placeholder="请输入部门职位" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="qq" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入qq" />
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="家乡" prop="home">
          <el-input v-model="form.home" placeholder="请输入家乡" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入城市" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置弹窗 -->
    <el-dialog title="设置权限" v-model="powerOpen" width="500px" append-to-body>
      <el-form ref="memberPowerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="power">
          <el-checkbox-group v-model="form.power">
            <div v-for="dict in dictTypeData" :key="dict.dictCode" class="checkbox-item">
              <el-checkbox :label="dict.dictCode" :name="dict.dictLabel">{{
                dict.dictLabel
              }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPowerForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember,
  getPower
} from "@/api/main/member";
import { getDicts } from "@/api/system/dict/data";
import { useRoute } from "vue-router";

const { proxy } = getCurrentInstance();
const isAdminType = ref([
  {
    label: "否",
    value: 0,
  },
  {
    label: "是",
    value: 1,
  },
]);

const memberList = ref([]);
const open = ref(false);
const powerOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const viewOpen = ref(false);
const powerDictType = ref("power_type");
const dictTypeData = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    circleId: null,
    nickName: null,
    phonenumber: null,
    department: null,
    email: null,
    qq: null,
    school: null,
    home: null,
    city: null,
    birthday: null,
    recommend: null,
    recomId: null,
    expireTime: null,
    dedication: null,
    shareNum: null,
    pullNum: null,
    isAdmin: 0,
    isGroup: null,
    isReceive: null,
    showNum: null,
    memo: null,
    status: null,
    createUser: null,
    createName: null,
    updateUser: null,
    updateName: null,
    company: null,
    summary: null,
    speciality: null,
    address: null,
    userId: null,
    department: null,
  },
  rules: {
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    delFlag: [
      { required: true, message: "是否删除;0否1是不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const route = useRoute();
console.log();

/** 查询圈成员列表 */
function getList() {
  loading.value = true;
  listMember(
    Object.assign(queryParams.value, {
      circleId: route.params?.id,
    })
  ).then((response) => {
    memberList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleIsAdmmin(e) {
  queryParams.value.isAdmin = e;
}

// 取消按钮
function cancel() {
  open.value = false;
  powerOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    circleId: null,
    nickName: null,
    phonenumber: null,
    department: null,
    email: null,
    qq: null,
    school: null,
    home: null,
    city: null,
    birthday: null,
    recommend: null,
    recomId: null,
    expireTime: null,
    dedication: null,
    shareNum: null,
    pullNum: null,
    isAdmin: null,
    isGroup: null,
    isReceive: null,
    showNum: null,
    memo: null,
    status: null,
    delFlag: null,
    createUser: null,
    createName: null,
    createTime: null,
    updateUser: null,
    updateName: null,
    updateTime: null,
    company: null,
    summary: null,
    speciality: null,
    address: null,
    userId: null,
    department: null,
    power: [],
  };
  proxy.resetForm("memberRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加圈成员";
}

/** 设置权限 */
function handlePower(row) {
  reset();
  form.value.id = row.id;
  form.value.circleId = row.circleId;
  form.value.userId = row.userId;
  if (row.power != null) {
    form.value.power = [...row.power];
  }
  dictTypeData.value = [];
  getDicts(powerDictType.value).then((response) => {
    dictTypeData.value = response.data;
  });
  // 获取用户权限
  getPower({ userId: row.userId, circleId: row.circleId }).then((response) => {
    if (response.code == 200) {
      let arr = [];
      if (response.data && response.data.length > 0) {
        response.data.forEach((item) => {
          arr.push(item.typeId);
        })
      }
      form.value.power = arr;
    }
  });

  powerOpen.value = true;
}

/** 提交权限设置 */
const submitData = ref([]);

const submitPowerForm = () => {
  proxy.$refs["memberPowerRef"].validate(async (valid) => {
    if (valid) {
      form.value.power.forEach((element) => {

        submitData.value.push({
          memberId: form.value.id,
          typeId: element,
          circleId: form.value.circleId,
        });
      });

      const newobject = {
        id: form.value.id,
        power: submitData.value,
        powerId: [],
      };

      const obj = Object.assign(newobject, data.queryParams);
      delete obj.isAdmin;
      obj.userId = form.value.userId;
      const response = await updateMember(obj);
      console.log(response);
      if (response && response.code == 200) {
        powerOpen.value = false;
        submitData.value = [];
        proxy.$modal.msgSuccess("操作成功");
      }
    }
  });
};

/** 提交权限设置 */
// function submitPowerForm() {
//   proxy.$refs["memberPowerRef"].validate((valid) => {
//     if (valid) {
//       let submitData = [];
//       form.value.power.forEach((element) => {
//         submitData.push({
//           memberId: form.value.id,
//           typeId: element,
//           circleId: form.value.circleId,
//         });
//       });
//       console.log(submitData);
//     }
//   });
// }

/** 设置管理员 */
function handleUpdate(row) {
  reset();
  form.value.id = row.id;
  form.value.userId = row.userId;
  if (row.isAdmin == 0) {
    form.value.isAdmin = 1;
  } else {
    form.value.isAdmin = 0;
  }
  let str =
    row.isAdmin == 0
      ? '是否确认设置圈成员"' + row.nickName + '"为群管理员？'
      : '是否确认取消设置圈成员"' + row.nickName + '"为群管理员？';
  proxy.$modal
    .confirm(str)
    .then(function () {
      return updateMember(form.value);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => { });
}

/** 修改按钮操作 */
function handleInfo(row) {
  reset();
  const _id = row.id || ids.value;
  getMember(_id).then((response) => {
    form.value = response.data;
    viewOpen.value = true;
    title.value = "查看详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateMember(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        const newObject = Object.assign(form.value, {
          circleId: route.params?.id,
        });
        addMember(newObject).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除圈成员编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delMember(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "main/member/export",
    {
      ...queryParams.value,
    },
    `member_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped lang="scss">
/* 确保每项独占一行 */
.checkbox-item {
  margin-bottom: 10px;
  /* 添加一些间距 */
}

:deep(.el-form-item__label) {
  display: flex;
  justify-content: flex-start;
  width: auto !important;
}
</style>
